package com.xique.park.utils;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 阿里小程序工具类
 * @author caogq
 */
@Component
@Slf4j
public class AlipayUtils {

    public static String getUserId(String authCode,String appid,String appPrivateKey,String appPublicKey) {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", appid, appPrivateKey, "json", "UTF-8", appPublicKey, "RSA2");
        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
        request.setCode(authCode);
        request.setGrantType("authorization_code");
        try {
            AlipaySystemOauthTokenResponse oauthTokenResponse = alipayClient.execute(request);
            log.info("获取支付宝authCode：{}，后端返回userId: {}",authCode,oauthTokenResponse.getUserId());
            return oauthTokenResponse.getUserId();
        } catch (AlipayApiException e) {
            //处理异常
            e.printStackTrace();
            return "";
        }
    }
}
